<?php
namespace Bundle\TreeBundle\Repository;

use Doctrine\ORM\EntityRepository;

class TreeRepository extends EntityRepository
{
    public function getSiteTree($parent = null)
    {
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb->select('t')->from($this->_entityName, 't');

        if($parent != null)
        {
            // WRONG!!!!!
            $qb->where('t.parent = ' . (int) $parent);
        }

        $qb->orderBy('t.order', 'ASC');

        $qb->addSelect('p')
                ->leftJoin('t.description', 'p');

        $preresult = $qb->getQuery()->getResult();

        $result = array();
        foreach($preresult as $item)
        {
            if($parent == null && $item->getParent() == null)
            {
                $result [] = $item;
            }
            else if($parent != null && $item->getParent() != null &&
                    $item->getParent()->getId() == $parent)
            {
                $result [] = $item;
            }
        }
        return $result;

    }

    public function findAll()
    {
        return $this->getEntityManager()->createQueryBuilder()
                ->select('t')->from($this->_entityName, 't')
                ->orderBy('t.order', 'ASC')->getQuery()->getResult();
        return parent::findAll();
    }

    public function readTree($id)
    {
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb->select('t')->from($this->_entityName, 't')
                ->where('t.id = ' . (int) $id);


        $qb->addSelect('p')
                ->leftJoin('t.description', 'p');

        return($qb->getQuery()->execute());
        return $this->getEntityManager()->createQueryBuilder()
                ->select('t')->from($this->_entityName, 't')
                ->addSelect('p')
                ->leftJoin('t.description', 'p')
                ->where('p.id = ' . (int) $id )
                ->getQuery()->execute();
    }
     //return $this->getEntityManager()->createQuery('SELECT l FROM Application\\Site1Bundle\\Entities\\Tree l Order BY l.parent ASC')->getResult();
    //return $this->_em->createQuery('SELECT l FROM Application\\ReadlaterBundle\\Entities\\Link l ORDER BY l.createdAt DESC')->getResult();
  

  //public function
}